<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>skuTest</title>
    <style>
        dl {
            border: 1px solid #aaa;
            padding: 10px;
        }

        dt {
            padding: 5px;
        }

        dd {
            display: inline-block;
            padding: 5px 10px;
            border: 1px solid #eee;
            user-select: none;
            cursor: pointer;
        }

        dd.active {
            color: #fff;
            background: lightcoral;
        }

        dd.disabled {
            color: #aaa;
            background: #eee;
        }
    </style>
</head>

<body>
    <div class="sku-info"></div>
    <div class="sku-wrapper">

    </div>
</body>
<script>
    var Sku = function (params) {
        this.sku = params.data
        this.container = document.querySelector(params.container) //sku容器
        this.skuInfoContainer = document.querySelector(params.skuInfoContainer)
        this.dd = null //节点容器
        this.items = []
        this.currentActive = []
        this.currentSku = {}
        this.priceCollection = []
    }
    //初始化
    Sku.prototype._init = function () {
        this._dataParse()
        this._itemDisabled()
        this._render()
        this._setSkuInfo()
    }
    //数据解析
    Sku.prototype._dataParse = function () {
        var items = []
        var temp = []
        for (var key in this.sku[0].attr) {
            if (this.sku[0].attr.hasOwnProperty(key)) {
                items.push({
                    name: key,
                    child: []
                })
                temp.push(key)
            }
        }
        for (var i = 0; i < items.length; i++) {
            var el = items[i]
            for (var j = 0; j < this.sku.length; j++) {
                var els = this.sku[j].attr[el.name]
                if (temp.indexOf(els) === -1) {
                    el.child.push({
                        disabled: 0,
                        active: 0,
                        name: els
                    })
                    temp.push(els)
                }
            }
        }
        this.items = items
    }
    //渲染sku列表
    Sku.prototype._render = function () {
        this.container.innerHTML = this.template()
        this._bind()
    }
    //生成模板
    Sku.prototype.template = function () {
        var html = "<dl>"
        for (var i = 0; i < this.items.length; i++) {
            var el = this.items[i];
            html += `<dt>${el.name}</dt>`
            for (var j = 0; j < el.child.length; j++) {
                var elj = el.child[j];
                html += `<dd 
                      class="${elj.active ? 'active ' : ' '}${elj.disabled ? 'disabled' : ''}"
                      data-index="${j}"
                      data-parent="${i}"
                      data-name="${elj.name}"
                      >${elj.name}</dd>`
            }
        }
        html += "</dl>"
        return html
    }
    //解绑按钮事件
    Sku.prototype._unbind = function () {
        for (var i = 0; i < this.dd.length; i++) {
            this.dd[i].onclick = null
            this.dd[i] = null
        }
    }
    //绑定点击按钮
    Sku.prototype._bind = function () {
        var that = this
        this.dd && this._unbind()
        this.dd = this.container.querySelectorAll("dd")
        for (var i = 0; i < this.dd.length; i++) {
            var el = this.dd[i]
            el.addEventListener("click", function () {
                if (this.classList.value.indexOf("disabled") > -1) return
                var parentIndex = this.dataset.parent
                var index = this.dataset.index
                var children = that.items[parentIndex].child
                for (var j = 0; j < children.length; j++) {
                    var elj = children[j];
                    if (this.classList.value.indexOf("active") > -1) {
                        elj.active = index == j ? 0 : elj.active
                        for (var a = 0; a < that.currentActive.length; a++) {
                            var ela = that.currentActive[a];
                            if (ela.key == that.items[parentIndex].name) {
                                that.currentActive.splice(a, 1)
                                break
                            }
                        }
                    } else {
                        elj.active = index == j ? 1 : 0
                        if (elj.active == 1) {
                            var flag = 0
                            for (var a = 0; a < that.currentActive.length; a++) {
                                var ela = that.currentActive[a];
                                if (ela.key == that.items[parentIndex].name) {
                                    ela.name = elj.name
                                    flag++
                                }
                            }!flag && that.currentActive.push({
                                key: that.items[parentIndex].name,
                                name: elj.name,
                                active:1
                            })
                        }
                    }
                }
                that._itemDisabled()
                that._setSkuInfo()
                that._render()
            })
        }

    }

    //判断是否disabled
    Sku.prototype._itemDisabled = function (parentIndex) {
        this.priceCollection = []
        this.currentSku = {}
        for (var item = 0; item < this.items.length; item++) {
            var eli = this.items[item]
            var currentActive = JSON.parse(JSON.stringify(this.currentActive))
            for (var c = 0; c < currentActive.length; c++) {
                        var elc = currentActive[c];
                        if(elc.key===eli.name) {
                            currentActive.splice(c,1)
                        }
                    }

            for (var a = 0; a < eli.child.length; a++) {
                var ela = eli.child[a]
                var elParentName = eli.name
                var _actives = []
                    _actives = currentActive.concat([{
                        key: elParentName,
                        name: ela.name,
                        active:ela.active
                    }])

                var disabled = 1
                for (var i = 0; i < this.sku.length; i++) {
                    var attrs = this.sku[i].attr;
                    var flag = 0
                    var active = 0
                    for (var j = 0; j < _actives.length; j++) {
                        var elActive = _actives[j];
                        if (attrs[elActive.key] == elActive.name && this.sku[i].stock != 0) {
                            flag++
                        }
                        if(elActive.active == 1) active++
                    }
                    if (flag == _actives.length) {
                        disabled = 0
                        if (this.priceCollection.indexOf(this.sku[i].price) === -1) {
                            this.priceCollection.push(this.sku[i].price)
                        }
                        if(active == this.items.length){
                            this.currentSku = this.sku[i]
                        }
                    }
                        
                }
                ela.disabled = disabled
            }
        }
    }
    //生成价格和id
    Sku.prototype._setSkuInfo = function () {
        var _max = Math.max.apply(null, this.priceCollection)
        var _min = Math.min.apply(null, this.priceCollection)
        var price = 0
        var skuId = ""

        if (this.currentActive.length === this.items.length) {
            skuId = this.currentSku.skuno
            price = this.currentSku.price
        }else{
            price = _max === _min ? _max : _min + "~" + _max
        }
        var html = `价格:${price}`
        if (skuId) html += ` 当前Skuno: ${skuId}`
        this.skuInfoContainer.innerHTML = html
    }


    var sku = new Sku({
        container: ".sku-wrapper",
        skuInfoContainer: ".sku-info",
        data: [{
                'skuno': '1',
                'attr': {
                    '颜色': '黑色',
                    '版本': '标准版',
                    '内存': '128G'
                },
                'stock': '12',
                'price': '1'
            }, {
                'skuno': '2',
                'attr': {
                    '颜色': '紫色',
                    '版本': '标准版',
                    '内存': '128G'
                },
                'stock': '0',
                'price': '2'
            },
            {
                'skuno': '3',
                'attr': {
                    '颜色': '红色',
                    '版本': '标准版',
                    '内存': '128G'
                },
                'stock': '11',
                'price': '3'
            },
            {
                'skuno': '4',
                'attr': {
                    '颜色': '蓝色',
                    '版本': '标准版',
                    '内存': '128G'
                },
                'stock': '0',
                'price': '4'
            },
            {
                'skuno': '5',
                'attr': {
                    '颜色': '黑色',
                    '版本': 'NFC版',
                    '内存': '128G'
                },
                'stock': '2',
                'price': '5'
            },
            {
                'skuno': '6',
                'attr': {
                    '颜色': '红色',
                    '版本': 'NFC版',
                    '内存': '128G'
                },
                'stock': '2',
                'price': '6'
            },
            {
                'skuno': '7',
                'attr': {
                    '颜色': '蓝色',
                    '版本': 'NFC版',
                    '内存': '128G'
                },
                'stock': '12',
                'price': '7'
            },
            {
                'skuno': '8',
                'attr': {
                    '颜色': '黑色',
                    '版本': 'NFC版',
                    '内存': '256G'
                },
                'stock': '0',
                'price': '8'
            },
            {
                'skuno': '9',
                'attr': {
                    '颜色': '红色',
                    '版本': 'NFC版',
                    '内存': '256G'
                },
                'stock': '12',
                'price': '9'
            },
            {
                'skuno': '10',
                'attr': {
                    '颜色': '蓝色',
                    '版本': 'NFC版',
                    '内存': '256G'
                },
                'stock': '12',
                'price': '10'
            },
        ]
    })
    sku._init()
</script>

</html>